/**
 * @Author: Sun Rising 
 * @Date: 2020-06-14 08:39:45 
 * @Last Modified by: Sun Rising
 * @Last Modified time: 2020-06-25 18:20:32
 * @Description: 表单容器
 */
<template>
  <div id="sunForm">
    <slot></slot>
    <uni-popup ref="popup" type="top" :isMaskShow="false">
      <uni-popup-message type="error" :message="exceptionMessage" :duration="1500"></uni-popup-message>
    </uni-popup>
  </div>
</template>

<script>
import uniPopup from "../uni-popup/uni-popup.vue";
import uniPopupMessage from "../uni-popup/uni-popup-message.vue";

// 元素集合
let fields = [];
export default {
  name: "sunForm",
  components: {
    uniPopup,
    uniPopupMessage
  },
  props: {
    // 标签宽度(rpx)
    labelWidth: {
      type: Number,
      default: 200
    },
    // 表单数据源
    model: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 显示错误信息
    showErrorMessage: {
      type: Boolean,
      default: true
    }
  },
  provide() {
    return {
      sunForm: this
    };
  },
  data() {
    return {
      // 异常信息
      exceptionMessage: ""
    };
  },
  methods: {
    // 注册元素
    doRegisteredElement(element) {
      fields.push(element);
    },
    // 显示错误信息
    doShowMessage(msg) {
      if (this.showErrorMessage) {
        this.exceptionMessage = msg;
        this.$refs["popup"].open();
      }
    },
    // 表单校验接口
    validate(isContinue = false) {
      return new Promise((resolve, reject) => {
        let errorMsgs = [];
        for (const fieldId of fields) {
          const message = fieldId.doValidate(this.model[fieldId.prop]);
          if (message) {
            errorMsgs.push(message);
            if (!isContinue) break;
          }
        }
        errorMsgs.length > 0 ? reject(errorMsgs) : resolve(errorMsgs);
      });
    }
  }
};
</script>

